package com.wangdao.wechatmall.service.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wangdao.wechatmall.bean.bo.admin.PermissionBO;
import com.wangdao.wechatmall.bean.bo.admin.RoleBO;
import com.wangdao.wechatmall.bean.bo.admin.RoleParamBO;
import com.wangdao.wechatmall.bean.pojo.*;
import com.wangdao.wechatmall.bean.vo.admin.*;
import com.wangdao.wechatmall.exception.RoleDuplicatedException;
import com.wangdao.wechatmall.exception.RoleEmptyException;
import com.wangdao.wechatmall.mapper.AdminMapper;
import com.wangdao.wechatmall.mapper.PermissionMapper;
import com.wangdao.wechatmall.bean.pojo.Role;
import com.wangdao.wechatmall.bean.pojo.RoleExample;
import com.wangdao.wechatmall.mapper.RoleMapper;
import com.wangdao.wechatmall.util.DateTransformUtil;
import com.wangdao.wechatmall.util.LoadFileUtils;
import com.wangdao.wechatmall.util.StringTransformUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import java.io.File;
import java.lang.System;
import java.util.*;

/**
 * @ClassName: RoleServiceImpl
 * @Description ${DESCRIPTION}
 * @Author Xinhao Yi
 * @Date 2021/7/9  1:47
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    AdminMapper adminMapper;

    @Autowired
    PermissionMapper permissionMapper;

    @Override
    public List<RoleVO> queryRole() {

        //创建example
        RoleExample roleExample = new RoleExample();

        //拿取roles
        List<Role> roles = roleMapper.selectByExample(roleExample);
        List<RoleVO> roleVOList = new ArrayList<>();
        for (Role role : roles) {
            RoleVO roleVO = new RoleVO();
            roleVO.setValue(role.getId());
            roleVO.setLabel(role.getName());
            roleVOList.add(roleVO);
        }

        return roleVOList;

    }

    @Override
    public RoleDataVO queryRole(RoleParamBO param) {
        //分页
        PageHelper.startPage(param.getPage(), param.getLimit());
        //根据name是否为null构造查询条件
        //根据sort和order去写排序
        //里面包含List<Criterion> 条件列表
        RoleExample roleExample = new RoleExample();
        RoleExample.Criteria criteria = roleExample.createCriteria();
        if (param.getName() != null) {
            criteria.andNameLike("%" + param.getName() + "%");
        }
        //一定要注意这里两者之间要有空格
        roleExample.setOrderByClause(param.getSort() + " " + param.getOrder());
        //查找，拿到角色序列
        List<Role> roles = roleMapper.selectByExample(roleExample);

        //创建用于保存结果的 adminVoList
        List<RoleBeanVO> roleBeanVOS = new ArrayList<>();
        for (Role role : roles) {
            RoleBeanVO roleBeanVO = new RoleBeanVO();
            //封装
            roleBeanVO.setId(role.getId());
            roleBeanVO.setName(role.getName());
            roleBeanVO.setDesc(role.getDesc());
            roleBeanVO.setEnabled(role.getEnabled());
            roleBeanVO.setAddTime(role.getAddTime());
            roleBeanVO.setUpdateTime(role.getUpdateTime());
            roleBeanVO.setDeleted(role.getDeleted());
            //add进roleBeanVOS中
            roleBeanVOS.add(roleBeanVO);
        }
        //再去拿去total
        //total可以使用countByExample，也可以使用PageHelper来获得
        //方法一：使用countByExample
        //int total = adminExample.countByExample(adminExample);

        //方法二：使用PageInfo
        //在执行查询之后可以获得分页信息,将查询结果放入PageInfo的构造方法里
        PageInfo<RoleBeanVO> pageInfo = new PageInfo<>(roleBeanVOS);
        int total = (int) pageInfo.getTotal();

        return RoleDataVO.ok(total, roleBeanVOS);
    }

    @Override
    public Role create(RoleBO param) throws RoleEmptyException, RoleDuplicatedException {
        //先检验参数
        //先进行数据校验
        //首先要判断param的数据是否为空
        if (StringUtils.isEmpty(param.getName()) || StringUtils.isEmpty(param.getDesc())) {
            throw new RoleEmptyException();
        }

        //查询角色的名字是否重复
        RoleExample adminExample = new RoleExample();
        RoleExample.Criteria criteria = adminExample.createCriteria();

        if (param.getName() != null) {
            criteria.andNameEqualTo(param.getName());
        }
        List<Role> roles = roleMapper.selectByExample(adminExample);
        if (roles.size() > 0) {
            throw new RoleDuplicatedException();
        }

        //创建插入到数据库的insertRole
        Role insertRole = new Role();
        insertRole.setName(param.getName());
        insertRole.setDesc(param.getDesc());
        insertRole.setEnabled(true);
        //当前时间戳
        Date date = new Date(System.currentTimeMillis());
        //调用工具类格式化时间
        Date dateFormatted = DateTransformUtil.dateFormat(date);
        insertRole.setAddTime(dateFormatted);
        insertRole.setUpdateTime(dateFormatted);
        insertRole.setDeleted(false);
        //插入
        int i = roleMapper.insertSelective(insertRole);

        //拿到新插入角色的id
        Integer id = roleMapper.selectMaxId();

        //创造用于返回的roleVO
        Role roleVO = new Role();
        roleVO.setId(id);
        roleVO.setName(param.getName());
        roleVO.setDesc(param.getDesc());
        roleVO.setAddTime(dateFormatted);
        roleVO.setUpdateTime(dateFormatted);

        return roleVO;

    }

    @Override
    public Integer update(Role param) throws RoleEmptyException {
        //先检验参数
        //先进行数据校验
        //首先要判断param的数据是否为空
        if (StringUtils.isEmpty(param.getName()) || StringUtils.isEmpty(param.getDesc())) {
            throw new RoleEmptyException();
        }
        //创建更新数据库用的updateRole
        Role updateRole = new Role();
        updateRole.setId(param.getId());
        updateRole.setName(param.getName());
        updateRole.setDesc(param.getDesc());
        updateRole.setEnabled(param.getEnabled());
        updateRole.setAddTime(param.getAddTime());

        //当前时间戳
        Date date = new Date(System.currentTimeMillis());
        //调用工具类格式化时间
        Date dateFormatted = DateTransformUtil.dateFormat(date);
        //更新时间
        updateRole.setUpdateTime(dateFormatted);
        updateRole.setDeleted(param.getDeleted());

        //更新数据库
        int i = roleMapper.updateByPrimaryKeySelective(updateRole);

        return i;
    }

    @Override
    public Boolean delete(Role param) {
        //我们需要查找这个角色是否被某个或某些管理员持有，只要这个角色被持有，它就不允许被删除
        //我的思路是查所有的admin，把拿到的role_id全放进一个set中，在把admin遍历完后，我们再去遍历set集合
        //如果有和我们param的id相同的，我们就不允许删除，否则允许删除
        Set<Integer> role_ids = new HashSet<>();
        //拿到全部的admin，然后遍历
        AdminExample adminExample = new AdminExample();
        List<Admin> admins = adminMapper.selectByExample(adminExample);
        for (Admin admin : admins) {
            List<Integer> ids = StringTransformUtils.integerArray2List(admin.getRoleIds());
            //放进set集合中
            for (Integer id : ids) {
                role_ids.add(id);
            }
        }
        //之后遍历set集合role_ids
        for (Integer role_id : role_ids) {
            if (role_id.equals(param.getId())) {
                //如果set里面有role_id，就返回false
                return false;
            }
        }
        //说明可以删除
        //删除这个角色
        Role deleteRole = new Role();
        deleteRole.setId(param.getId());
        deleteRole.setDeleted(true);
        //更新数据库
        int i = roleMapper.updateByPrimaryKeySelective(deleteRole);
        //返回true
        return true;
    }

    /**
     * 查找该角色全部的permission并且格式化输出
     *
     * @param param
     * @return
     */
    @Override
    public PermissionVO queryPermissionsGet(Permission param) {
        PermissionExample permissionExample = new PermissionExample();
        PermissionExample.Criteria criteria = permissionExample.createCriteria();
        if (param.getRoleId() != null) {
            criteria.andRoleIdEqualTo(param.getRoleId());
        }
        //拿到该角色全部的permissions
        List<Permission> permissions = permissionMapper.selectByExample(permissionExample);
        //创建一个返回类中需要用到的保存完整api的list
        List<String> assignedPermissions = new ArrayList<>();
        //填充它
        for (Permission permission : permissions) {
            //拿到字符串Permission，也就是api的字符串
            String permissionString = permission.getPermission();
            //顺便把这个api加到咱们保存完整api的assignedPermissions中来
            assignedPermissions.add(permissionString);
        }

        //从api.txt中拿到全部的api并生成list
        List<String> permissionApiList = null;
        try {
            File file = new ClassPathResource("permissions.txt").getFile();
            permissionApiList = LoadFileUtils.getFileContext(file);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //超级管理员的permission用 *
        if (assignedPermissions.get(0).equals("*")){
            //如果拿到的是*，说明是超级管理员，assignedPermissions应该是全部的api
            //直接赋值即可
            assignedPermissions = permissionApiList;
        }



        //格式化拼接出我们想要的PermissionVO
        //咱们要根据这些api拼出一个嵌套的map来，再逐层遍历这个map来得到我们的返回结果
        //嵌套map
        Map<String, Map<String, List<PermissionSecondChildrenVO>>> outsideMap = new HashMap<>();

        //如果permissionApiList为空，那么直接return一个null即可，就不要走后面了
        if (permissionApiList == null) {
            return null;
        }

        //开始循环
        //咱们循环两次，第一次循环，把内层map有哪些都创建好，比如其中一个内层map{"管理员管理","角色管理","对象存储","操作日志"}，第二次循环再去填充对应的内层map
        for (String permissionString : permissionApiList) {

            //permissionString是api的字符串
            //用冒号把api分开
            String[] splitPermissions = permissionString.split(":");
            //拿到第二个字符，来检查它是什么
            String secondPermissionWord = splitPermissions[1];
            //拿到第三个字符，后面会用到
            String thirdPermissionWord = splitPermissions[2];

            //记录一下lableFirstLevel和lableSecondLevel
            String lableFirstLevel = "";
            String lableSecondLevel = "";

            switch (secondPermissionWord) {
                /*
                系统管理
                 */
                case "admin":
                    //把内部map放进外部map中
                    //如果对应的内部map不存在，就创建一个内部map放进去
                {
                    lableFirstLevel = "系统管理";
                    lableSecondLevel = "管理员管理";
                    if (!outsideMap.containsKey("系统管理")) {
                        outsideMap.put("系统管理", new HashMap<>());
                    }
                    //拿到内部map，并把list放进去
                    Map<String, List<PermissionSecondChildrenVO>> insideMap = outsideMap.get("系统管理");
                    if (!insideMap.containsKey("管理员管理")) {
                        insideMap.put("管理员管理", new ArrayList<>());
                    }
                    break;
                }
                case "role":
                    //把内部map放进外部map中
                    //如果对应的内部map不存在，就创建一个内部map放进去
                {
                    lableFirstLevel = "系统管理";
                    lableSecondLevel = "角色管理";
                    if (!outsideMap.containsKey("系统管理")) {
                        outsideMap.put("系统管理", new HashMap<>());
                    }
                    //拿到内部map，并把list放进去
                    Map<String, List<PermissionSecondChildrenVO>> insideMap = outsideMap.get("系统管理");
                    if (!insideMap.containsKey("角色管理")) {
                        insideMap.put("角色管理", new ArrayList<>());
                    }
                    break;
                }
                case "storage":
                    //把内部map放进外部map中
                    //如果对应的内部map不存在，就创建一个内部map放进去
                {
                    lableFirstLevel = "系统管理";
                    lableSecondLevel = "对象存储";
                    if (!outsideMap.containsKey("系统管理")) {
                        outsideMap.put("系统管理", new HashMap<>());
                    }
                    //拿到内部map，并把list放进去
                    Map<String, List<PermissionSecondChildrenVO>> insideMap = outsideMap.get("系统管理");
                    if (!insideMap.containsKey("对象存储")) {
                        insideMap.put("对象存储", new ArrayList<>());
                    }
                    break;
                }
                case "log":
                    //把内部map放进外部map中
                    //如果对应的内部map不存在，就创建一个内部map放进去
                {
                    lableFirstLevel = "系统管理";
                    lableSecondLevel = "操作日志";
                    if (!outsideMap.containsKey("系统管理")) {
                        outsideMap.put("系统管理", new HashMap<>());
                    }
                    //拿到内部map，并把list放进去
                    Map<String, List<PermissionSecondChildrenVO>> insideMap = outsideMap.get("系统管理");
                    if (!insideMap.containsKey("操作日志")) {
                        insideMap.put("操作日志", new ArrayList<>());
                    }
                    break;
                }
                /*
                商场管理
                 */
                case "brand":
                    //把内部map放进外部map中
                    //如果对应的内部map不存在，就创建一个内部map放进去
                {
                    lableFirstLevel = "商场管理";
                    lableSecondLevel = "品牌管理";
                    if (!outsideMap.containsKey("商场管理")) {
                        outsideMap.put("商场管理", new HashMap<>());
                    }
                    //拿到内部map，并把list放进去
                    Map<String, List<PermissionSecondChildrenVO>> insideMap = outsideMap.get("商场管理");
                    if (!insideMap.containsKey("品牌管理")) {
                        insideMap.put("品牌管理", new ArrayList<>());
                    }
                    break;
                }
                case "issue":
                    //把内部map放进外部map中
                    //如果对应的内部map不存在，就创建一个内部map放进去
                {
                    lableFirstLevel = "商场管理";
                    lableSecondLevel = "通用问题";
                    if (!outsideMap.containsKey("商场管理")) {
                        outsideMap.put("商场管理", new HashMap<>());
                    }
                    //拿到内部map，并把list放进去
                    Map<String, List<PermissionSecondChildrenVO>> insideMap = outsideMap.get("商场管理");
                    if (!insideMap.containsKey("通用问题")) {
                        insideMap.put("通用问题", new ArrayList<>());
                    }
                    break;
                }
                case "order":
                    //把内部map放进外部map中
                    //如果对应的内部map不存在，就创建一个内部map放进去
                {
                    lableFirstLevel = "商场管理";
                    lableSecondLevel = "订单管理";
                    if (!outsideMap.containsKey("商场管理")) {
                        outsideMap.put("商场管理", new HashMap<>());
                    }
                    //拿到内部map，并把list放进去
                    Map<String, List<PermissionSecondChildrenVO>> insideMap = outsideMap.get("商场管理");
                    if (!insideMap.containsKey("订单管理")) {
                        insideMap.put("订单管理", new ArrayList<>());
                    }
                    break;
                }
                case "category":
                    //把内部map放进外部map中
                    //如果对应的内部map不存在，就创建一个内部map放进去
                {
                    lableFirstLevel = "商场管理";
                    lableSecondLevel = "类目管理";
                    if (!outsideMap.containsKey("商场管理")) {
                        outsideMap.put("商场管理", new HashMap<>());
                    }
                    //拿到内部map，并把list放进去
                    Map<String, List<PermissionSecondChildrenVO>> insideMap = outsideMap.get("商场管理");
                    if (!insideMap.containsKey("类目管理")) {
                        insideMap.put("类目管理", new ArrayList<>());
                    }
                    break;
                }
                case "keyword":
                    //把内部map放进外部map中
                    //如果对应的内部map不存在，就创建一个内部map放进去
                {
                    lableFirstLevel = "商场管理";
                    lableSecondLevel = "关键词";
                    if (!outsideMap.containsKey("商场管理")) {
                        outsideMap.put("商场管理", new HashMap<>());
                    }
                    //拿到内部map，并把list放进去
                    Map<String, List<PermissionSecondChildrenVO>> insideMap = outsideMap.get("商场管理");
                    if (!insideMap.containsKey("关键词")) {
                        insideMap.put("关键词", new ArrayList<>());
                    }
                    break;
                }
                /*
                用户管理
                 */
                case "collect":
                    //把内部map放进外部map中
                    //如果对应的内部map不存在，就创建一个内部map放进去
                {
                    lableFirstLevel = "用户管理";
                    lableSecondLevel = "用户收藏";
                    if (!outsideMap.containsKey("用户管理")) {
                        outsideMap.put("用户管理", new HashMap<>());
                    }
                    //拿到内部map，并把list放进去
                    Map<String, List<PermissionSecondChildrenVO>> insideMap = outsideMap.get("用户管理");
                    if (!insideMap.containsKey("用户收藏")) {
                        insideMap.put("用户收藏", new ArrayList<>());
                    }
                    break;
                }
                case "footprint":
                    //把内部map放进外部map中
                    //如果对应的内部map不存在，就创建一个内部map放进去
                {
                    lableFirstLevel = "用户管理";
                    lableSecondLevel = "用户足迹";
                    if (!outsideMap.containsKey("用户管理")) {
                        outsideMap.put("用户管理", new HashMap<>());
                    }
                    //拿到内部map，并把list放进去
                    Map<String, List<PermissionSecondChildrenVO>> insideMap = outsideMap.get("用户管理");
                    if (!insideMap.containsKey("用户足迹")) {
                        insideMap.put("用户足迹", new ArrayList<>());
                    }
                    break;
                }
                case "feedback":
                    //把内部map放进外部map中
                    //如果对应的内部map不存在，就创建一个内部map放进去
                {
                    lableFirstLevel = "用户管理";
                    lableSecondLevel = "意见反馈";
                    if (!outsideMap.containsKey("用户管理")) {
                        outsideMap.put("用户管理", new HashMap<>());
                    }
                    //拿到内部map，并把list放进去
                    Map<String, List<PermissionSecondChildrenVO>> insideMap = outsideMap.get("用户管理");
                    if (!insideMap.containsKey("意见反馈")) {
                        insideMap.put("意见反馈", new ArrayList<>());
                    }
                    break;
                }
                case "history":
                    //把内部map放进外部map中
                    //如果对应的内部map不存在，就创建一个内部map放进去
                {
                    lableFirstLevel = "用户管理";
                    lableSecondLevel = "搜索历史";
                    if (!outsideMap.containsKey("用户管理")) {
                        outsideMap.put("用户管理", new HashMap<>());
                    }
                    //拿到内部map，并把list放进去
                    Map<String, List<PermissionSecondChildrenVO>> insideMap = outsideMap.get("用户管理");
                    if (!insideMap.containsKey("搜索历史")) {
                        insideMap.put("搜索历史", new ArrayList<>());
                    }
                    break;
                }
                case "user":
                    //把内部map放进外部map中
                    //如果对应的内部map不存在，就创建一个内部map放进去
                {
                    lableFirstLevel = "用户管理";
                    lableSecondLevel = "会员管理";
                    if (!outsideMap.containsKey("用户管理")) {
                        outsideMap.put("用户管理", new HashMap<>());
                    }
                    //拿到内部map，并把list放进去
                    Map<String, List<PermissionSecondChildrenVO>> insideMap = outsideMap.get("用户管理");
                    if (!insideMap.containsKey("会员管理")) {
                        insideMap.put("会员管理", new ArrayList<>());
                    }
                    break;
                }
                case "address":
                    //把内部map放进外部map中
                    //如果对应的内部map不存在，就创建一个内部map放进去
                {
                    lableFirstLevel = "用户管理";
                    lableSecondLevel = "收货地址";
                    if (!outsideMap.containsKey("用户管理")) {
                        outsideMap.put("用户管理", new HashMap<>());
                    }
                    //拿到内部map，并把list放进去
                    Map<String, List<PermissionSecondChildrenVO>> insideMap = outsideMap.get("用户管理");
                    if (!insideMap.containsKey("收货地址")) {
                        insideMap.put("收货地址", new ArrayList<>());
                    }
                    break;
                }
                /*
                配置管理
                 */
                case "config":
                    //配置管理config比较特殊，要查找config后面一个字段nextKeyWord才能确定具体是哪个功能
                {
                    lableFirstLevel = "配置管理";

                    //先把内部map创建好
                    if (!outsideMap.containsKey("配置管理")) {
                        outsideMap.put("配置管理", new HashMap<>());
                    }
                    //查找config后面一个字段nextKeyWord
                    //再来确定内部map里面的各个key
                    String nextKeyWord = splitPermissions[2];
                    if ("wx".equals(nextKeyWord)) {
                        lableSecondLevel = "小程序配置";
                        //拿到内部map，并把list放进去
                        Map<String, List<PermissionSecondChildrenVO>> insideMap = outsideMap.get("配置管理");
                        if (!insideMap.containsKey("小程序配置")) {
                            insideMap.put("小程序配置", new ArrayList<>());
                        }
                    } else if ("express".equals(nextKeyWord)) {
                        lableSecondLevel = "运费配置";
                        //拿到内部map，并把list放进去
                        Map<String, List<PermissionSecondChildrenVO>> insideMap = outsideMap.get("配置管理");
                        if (!insideMap.containsKey("运费配置")) {
                            insideMap.put("运费配置", new ArrayList<>());
                        }
                    } else if ("mall".equals(nextKeyWord)) {
                        lableSecondLevel = "商场配置";
                        //拿到内部map，并把list放进去
                        Map<String, List<PermissionSecondChildrenVO>> insideMap = outsideMap.get("配置管理");
                        if (!insideMap.containsKey("商场配置")) {
                            insideMap.put("商场配置", new ArrayList<>());
                        }
                    } else if ("order".equals(nextKeyWord)) {
                        lableSecondLevel = "订单配置";
                        //拿到内部map，并把list放进去
                        Map<String, List<PermissionSecondChildrenVO>> insideMap = outsideMap.get("配置管理");
                        if (!insideMap.containsKey("订单配置")) {
                            insideMap.put("订单配置", new ArrayList<>());
                        }
                    }
                    break;
                }

                /*
                推广管理
                 */
                case "ad":
                    //把内部map放进外部map中
                    //如果对应的内部map不存在，就创建一个内部map放进去
                {
                    lableFirstLevel = "推广管理";
                    lableSecondLevel = "广告管理";
                    if (!outsideMap.containsKey("推广管理")) {
                        outsideMap.put("推广管理", new HashMap<>());
                    }
                    //拿到内部map，并把list放进去
                    Map<String, List<PermissionSecondChildrenVO>> insideMap = outsideMap.get("推广管理");
                    if (!insideMap.containsKey("广告管理")) {
                        insideMap.put("广告管理", new ArrayList<>());
                    }
                    break;
                }
                case "topic":
                    //把内部map放进外部map中
                    //如果对应的内部map不存在，就创建一个内部map放进去
                {
                    lableFirstLevel = "推广管理";
                    lableSecondLevel = "专题管理";
                    if (!outsideMap.containsKey("推广管理")) {
                        outsideMap.put("推广管理", new HashMap<>());
                    }
                    //拿到内部map，并把list放进去
                    Map<String, List<PermissionSecondChildrenVO>> insideMap = outsideMap.get("推广管理");
                    if (!insideMap.containsKey("专题管理")) {
                        insideMap.put("专题管理", new ArrayList<>());
                    }
                    break;
                }
                case "coupon":
                    //把内部map放进外部map中
                    //如果对应的内部map不存在，就创建一个内部map放进去
                {
                    lableFirstLevel = "推广管理";
                    lableSecondLevel = "优惠劵管理";
                    if (!outsideMap.containsKey("推广管理")) {
                        outsideMap.put("推广管理", new HashMap<>());
                    }
                    //拿到内部map，并把list放进去
                    Map<String, List<PermissionSecondChildrenVO>> insideMap = outsideMap.get("推广管理");
                    if (!insideMap.containsKey("优惠劵管理")) {
                        insideMap.put("优惠劵管理", new ArrayList<>());
                    }
                    break;
                }
                case "groupon":
                    //把内部map放进外部map中
                    //如果对应的内部map不存在，就创建一个内部map放进去
                {
                    lableFirstLevel = "推广管理";
                    lableSecondLevel = "团购管理";
                    if (!outsideMap.containsKey("推广管理")) {
                        outsideMap.put("推广管理", new HashMap<>());
                    }
                    //拿到内部map，并把list放进去
                    Map<String, List<PermissionSecondChildrenVO>> insideMap = outsideMap.get("推广管理");
                    if (!insideMap.containsKey("团购管理")) {
                        insideMap.put("团购管理", new ArrayList<>());
                    }
                    break;
                }
                /*
                商品管理
                 */
                case "goods":
                    //把内部map放进外部map中
                    //如果对应的内部map不存在，就创建一个内部map放进去
                {
                    lableFirstLevel = "商品管理";
                    lableSecondLevel = "商品管理";
                    if (!outsideMap.containsKey("商品管理")) {
                        outsideMap.put("商品管理", new HashMap<>());
                    }
                    //拿到内部map，并把list放进去
                    Map<String, List<PermissionSecondChildrenVO>> insideMap = outsideMap.get("商品管理");
                    if (!insideMap.containsKey("商品管理")) {
                        insideMap.put("商品管理", new ArrayList<>());
                    }
                    break;
                }
                case "comment":
                    //把内部map放进外部map中
                    //如果对应的内部map不存在，就创建一个内部map放进去
                {
                    lableFirstLevel = "商品管理";
                    lableSecondLevel = "评论管理";
                    if (!outsideMap.containsKey("商品管理")) {
                        outsideMap.put("商品管理", new HashMap<>());
                    }
                    //拿到内部map，并把list放进去
                    Map<String, List<PermissionSecondChildrenVO>> insideMap = outsideMap.get("商品管理");
                    if (!insideMap.containsKey("评论管理")) {
                        insideMap.put("评论管理", new ArrayList<>());
                    }
                    break;
                }

                /*
                其他
                 */
                case "index":
                    //把内部map放进外部map中
                    //如果对应的内部map不存在，就创建一个内部map放进去
                {
                    lableFirstLevel = "其他";
                    lableSecondLevel = "权限测试";
                    if (!outsideMap.containsKey("其他")) {
                        outsideMap.put("其他", new HashMap<>());
                    }
                    //拿到内部map，并把list放进去
                    Map<String, List<PermissionSecondChildrenVO>> insideMap = outsideMap.get("其他");
                    if (!insideMap.containsKey("权限测试")) {
                        insideMap.put("权限测试", new ArrayList<>());
                    }
                    break;
                }
                /*
                统计管理
                 */
                case "stat":
                    //统计管理stat比较特殊，要坚持后面一个字段才能确定功能
                {
                    lableFirstLevel = "统计管理";

                    if (!outsideMap.containsKey("统计管理")) {
                        outsideMap.put("统计管理", new HashMap<>());
                    }
                    //查找config后面一个字段nextKeyWord
                    //再来确定内部map里面的各个key
                    String nextKeyWord = splitPermissions[2];
                    if ("user".equals(nextKeyWord)) {
                        lableSecondLevel = "用户统计";
                        //拿到内部map，并把list放进去
                        Map<String, List<PermissionSecondChildrenVO>> insideMap = outsideMap.get("统计管理");
                        if (!insideMap.containsKey("用户统计")) {
                            insideMap.put("用户统计", new ArrayList<>());
                        }
                    } else if ("order".equals(nextKeyWord)) {
                        lableSecondLevel = "订单统计";
                        //拿到内部map，并把list放进去
                        Map<String, List<PermissionSecondChildrenVO>> insideMap = outsideMap.get("统计管理");
                        if (!insideMap.containsKey("订单统计")) {
                            insideMap.put("订单统计", new ArrayList<>());
                        }
                    } else if ("goods".equals(nextKeyWord)) {
                        lableSecondLevel = "商品统计";
                        //拿到内部map，并把list放进去
                        Map<String, List<PermissionSecondChildrenVO>> insideMap = outsideMap.get("统计管理");
                        if (!insideMap.containsKey("商品统计")) {
                            insideMap.put("商品统计", new ArrayList<>());
                        }
                    }
                    break;
                }
            }

            //这之后我们就要用api填充内部表insideMap
            //首先根据lableFirstLevel和lableSecondLevel拿到最底层的List<PermissionSecondChildrenVO>
            List<PermissionSecondChildrenVO> childList = outsideMap.get(lableFirstLevel).get(lableSecondLevel);
            //再拿到我们要封装的对象
            PermissionSecondChildrenVO childrenBean = new PermissionSecondChildrenVO();

            //然后我们应该先去处理比较特殊的api
            //系统管理----->角色管理
            if ("角色管理".equals(lableSecondLevel)) {
                //权限变更和权限详情的区分
                //权限变更
                if ("admin:role:permission:update".equals(permissionString)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getPOSTApi(permissionString));
                    childrenBean.setLabel("权限变更");
                }
                //权限详情
                else if ("admin:role:permission:get".equals(permissionString)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getGETApi(permissionString));
                    childrenBean.setLabel("权限详情");
                }
                //角色编辑
                else if ("update".equals(thirdPermissionWord)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getPOSTApi(permissionString));
                    childrenBean.setLabel("角色编辑");
                }
                //角色查询
                else if ("list".equals(thirdPermissionWord)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getGETApi(permissionString));
                    childrenBean.setLabel("角色查询");
                }
                //角色详情
                else if ("read".equals(thirdPermissionWord)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getGETApi(permissionString));
                    childrenBean.setLabel("角色详情");
                }
                //角色删除
                else if ("delete".equals(thirdPermissionWord)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getPOSTApi(permissionString));
                    childrenBean.setLabel("角色删除");
                }
                //角色添加
                else if ("create".equals(thirdPermissionWord)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getPOSTApi(permissionString));
                    childrenBean.setLabel("角色添加");
                }
            }

            //商场管理----->订单管理
            else if ("订单管理".equals(lableSecondLevel)) {
                //详情
                if ("detail".equals(thirdPermissionWord)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getGETApi(permissionString));
                    childrenBean.setLabel("详情");
                }
                //订单发货
                else if ("ship".equals(thirdPermissionWord)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getPOSTApi(permissionString));
                    childrenBean.setLabel("订单发货");
                }
                //订单退货
                else if ("refund".equals(thirdPermissionWord)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getPOSTApi(permissionString));
                    childrenBean.setLabel("订单退款");
                }
                //订单商品回复
                else if ("reply".equals(thirdPermissionWord)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getPOSTApi(permissionString));
                    childrenBean.setLabel("订单商品回复");
                }
                //查询
                else if ("list".equals(thirdPermissionWord)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getGETApi(permissionString));
                    childrenBean.setLabel("查询");
                }

            }

            //配置管理 ------> 底下的都要特殊处理
            //lableFirstLevel一级标签
            else if ("配置管理".equals(lableFirstLevel)) {
                if ("updateConfigs".equals(splitPermissions[3])) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getPOSTApi(permissionString));
                    childrenBean.setLabel("编辑");
                } else if ("list".equals(splitPermissions[3])) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getGETApi(permissionString));
                    childrenBean.setLabel("详情");
                }
            }

            //推广管理----->优惠劵管理
            else if ("优惠劵管理".equals(lableSecondLevel)) {
                if ("listuser".equals(thirdPermissionWord)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getGETApi(permissionString));
                    childrenBean.setLabel("查询用户");
                }
                if ("update".equals(thirdPermissionWord)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getPOSTApi(permissionString));
                    childrenBean.setLabel("编辑");
                } else if ("list".equals(thirdPermissionWord)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getGETApi(permissionString));
                    childrenBean.setLabel("查询");
                } else if ("read".equals(thirdPermissionWord)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getGETApi(permissionString));
                    childrenBean.setLabel("详情");
                } else if ("delete".equals(thirdPermissionWord)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getPOSTApi(permissionString));
                    childrenBean.setLabel("删除");
                } else if ("create".equals(thirdPermissionWord)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getPOSTApi(permissionString));
                    childrenBean.setLabel("添加");
                }
            }

            //推广管理----->团购管理
            else if ("团购管理".equals(lableSecondLevel)) {
                if ("listRecord".equals(thirdPermissionWord)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getGETApi(permissionString));
                    childrenBean.setLabel("详情");
                }
                if ("update".equals(thirdPermissionWord)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getPOSTApi(permissionString));
                    childrenBean.setLabel("编辑");
                } else if ("list".equals(thirdPermissionWord)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getGETApi(permissionString));
                    childrenBean.setLabel("查询");
                } else if ("delete".equals(thirdPermissionWord)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getPOSTApi(permissionString));
                    childrenBean.setLabel("删除");
                } else if ("create".equals(thirdPermissionWord)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getPOSTApi(permissionString));
                    childrenBean.setLabel("添加");
                }
            }

            //商品管理------>商品管理
            else if ("商品管理".equals(lableSecondLevel)) {
                //详情
                if ("detail".equals(thirdPermissionWord)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getGETApi(permissionString));
                    childrenBean.setLabel("详情");
                }
                //编辑
                if ("update".equals(thirdPermissionWord)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getPOSTApi(permissionString));
                    childrenBean.setLabel("编辑");
                }
                //查询
                if ("list".equals(thirdPermissionWord)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getGETApi(permissionString));
                    childrenBean.setLabel("查询");
                }
                //删除
                if ("delete".equals(thirdPermissionWord)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getPOSTApi(permissionString));
                    childrenBean.setLabel("删除");
                }
                //上架
                else if ("create".equals(thirdPermissionWord)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getPOSTApi(permissionString));
                    childrenBean.setLabel("上架");
                }
            }

            //其他---->权限测试
            else if ("权限测试".equals(lableSecondLevel)) {
                //权限写
                if ("write".equals(thirdPermissionWord)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getPOSTApi(permissionString));
                    childrenBean.setLabel("权限写");
                }
                //权限读
                else if ("read".equals(thirdPermissionWord)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getGETApi(permissionString));
                    childrenBean.setLabel("权限读");
                }
            }

            //统计管理 ------>底下的都要特殊处理
            //lableFirstLevel一级标签
            else if ("统计管理".equals(lableFirstLevel)) {
                if ("user".equals(thirdPermissionWord)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getPOSTApi(permissionString));
                    childrenBean.setLabel("查询");
                } else if ("order".equals(thirdPermissionWord)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getGETApi(permissionString));
                    childrenBean.setLabel("查询");
                } else if ("goods".equals(thirdPermissionWord)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getGETApi(permissionString));
                    childrenBean.setLabel("查询");
                }
            }
            //剩下的都是普通的增删改查api，统一处理即可
            //编辑、查询、详情、删除、添加
            else {
                if ("update".equals(thirdPermissionWord)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getPOSTApi(permissionString));
                    childrenBean.setLabel("编辑");
                } else if ("list".equals(thirdPermissionWord)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getGETApi(permissionString));
                    childrenBean.setLabel("查询");
                } else if ("read".equals(thirdPermissionWord)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getGETApi(permissionString));
                    childrenBean.setLabel("详情");
                } else if ("delete".equals(thirdPermissionWord)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getPOSTApi(permissionString));
                    childrenBean.setLabel("删除");
                } else if ("create".equals(thirdPermissionWord)) {
                    childrenBean.setId(permissionString);
                    childrenBean.setApi(getPOSTApi(permissionString));
                    childrenBean.setLabel("添加");
                }
            }
            //到这里我们的childrenBean肯定就组装好了，直接add进list中即可
            childList.add(childrenBean);
        }

        //到这里我们已经拼出了一个完整的嵌套map，里面有我们需要的组成返回类的所有信息
        //创建一个封装最后结果之一的systemPermissions
        List<PermissionSystemVO> systemPermissions = new ArrayList<>();
        //然后遍历这个map即可
        Set<Map.Entry<String, Map<String, List<PermissionSecondChildrenVO>>>> entries = outsideMap.entrySet();
        for (Map.Entry<String, Map<String, List<PermissionSecondChildrenVO>>> entry : entries) {
            //创建用于封装数据的外围对象
            PermissionSystemVO permissionSystemVO = new PermissionSystemVO();
            String id = entry.getKey();
            String label = entry.getKey();
            permissionSystemVO.setId(id);
            permissionSystemVO.setLabel(label);
            //把List<PermissionFirstChildVO> child先创造出来，等下再来往里面填数据
            List<PermissionFirstChildVO> children = new ArrayList<>();

            //拿到一个内部map
            Map<String, List<PermissionSecondChildrenVO>> innerMap = entry.getValue();
            //遍历这个内部map
            Set<Map.Entry<String, List<PermissionSecondChildrenVO>>> innerEntries = innerMap.entrySet();
            for (Map.Entry<String, List<PermissionSecondChildrenVO>> innerEntry : innerEntries) {
                //创建一个用于封装内层数据的对象
                PermissionFirstChildVO permissionFirstChildVO = new PermissionFirstChildVO();
                //拿id
                String innerId = innerEntry.getKey();
                //拿label
                String innerLabel = innerEntry.getKey();
                //拿底层的list
                List<PermissionSecondChildrenVO> value = innerEntry.getValue();
                //封装数据
                permissionFirstChildVO.setId(innerId);
                permissionFirstChildVO.setLabel(innerLabel);
                permissionFirstChildVO.setChildren(value);
                //add到我们的List<PermissionFirstChildVO> children中
                children.add(permissionFirstChildVO);
            }
            //把PermissionSystemVO类中的List<PermissionFirstChildVO> children这一项给填充进去
            permissionSystemVO.setChildren(children);
            //然后把permissionSystemVO也add到List<PermissionSystemVO> systemPermissions中去
            systemPermissions.add(permissionSystemVO);
        }

        //创建最终用于返回的对象permissionVO
        PermissionVO permissionVO = new PermissionVO();
        permissionVO.setSystemPermissions(systemPermissions);
        permissionVO.setAssignedPermissions(assignedPermissions);

        //返回我们封装好的结果
        return permissionVO;
    }

    //更新某个角色的api
    @Override
    public Integer queryPermissionsPost(PermissionBO param) {
        //我们的思路是先删后插入
        Integer roleId = param.getRoleId();

        //检查一下roleId，如果是1，说明是系统默认的超级管理员我们不允许去修改,直接返回404即可
        if (roleId == 1){
            return 404;
        }

        //新的permissions
        List<String> permissions = param.getPermissions();
        //在数据库中删掉该角色原来的permissions
        PermissionExample permissionExample = new PermissionExample();
        PermissionExample.Criteria criteria = permissionExample.createCriteria();
        criteria.andRoleIdEqualTo(roleId);
        //先拿到原来的数据
        List<Permission> originalPermissions = permissionMapper.selectByExample(permissionExample);
        //再删掉原来的数据
        int i = permissionMapper.deleteByExample(permissionExample);
        //生成时间
        //当前时间戳
        Date date = new Date(System.currentTimeMillis());
        //调用工具类格式化时间
        Date dateFormatted = DateTransformUtil.dateFormat(date);

        //检查经过调整后这个管理员是不是超级管理员

        //从api.txt中拿到全部的api并生成list
        List<String> permissionApiList = null;
        try {
            File file = new ClassPathResource("permissions.txt").getFile();
            permissionApiList = LoadFileUtils.getFileContext(file);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //如果permissionApiList为null，直接return 不用继续了
        if (permissionApiList == null){
            return 405;
        }

        //如果新的perimissions和全部permissions规模相同，那么就认为这个角色也成为了一个超级管理员,应该插入*，然后直接结束即可
        //同时如果这个角色原来的id也为1，那么它其实是咱们默认的超级管理员，它的权限为*，且id为1，
        //上面这句话有问题了，因为我们已经不允许修改超级管理员了
        if (permissionApiList.size() == permissions.size()){
            Permission permission = new Permission();
            permission.setRoleId(roleId);
            permission.setPermission("*");
            permission.setAddTime(dateFormatted);
            permission.setUpdateTime(dateFormatted);
            permission.setDeleted(false);
            permissionMapper.insertSelective(permission);
            return 200;
        }

        //插入新数据
        for (String s : permissions) {

            Permission permission = new Permission();
            permission.setRoleId(roleId);
            permission.setPermission(s);
            permission.setAddTime(dateFormatted);
            permission.setUpdateTime(dateFormatted);
            permission.setDeleted(false);
            int i1 = permissionMapper.insertSelective(permission);
        }

        return 200;
    }

    @Override
    public List<String> queryNameByRoleId(Integer[] roleIds) {
        List<String> roles = new ArrayList<>();
        for (int i = 0; i < roleIds.length; i++) {
            List<String> strings = new ArrayList<>();
            strings = roleMapper.selectNameByRoleId(roleIds[i]);
            roles.addAll(strings);

        }
        return roles;
    }

//    @Override
//    public List<String> queryNameByRoleId(Integer roleIds) {
//        List<String> strings = roleMapper.queryNameByRoleId(roleIds);
//        return strings;
//    }


    /**
     * 工具类，生成GET api
     *
     * @param permissionString
     * @return
     */
    //输入
    //"admin:admin:create"
    //"admin:role:permission:update"
    //结果：GET /admin/role/permissions
    private static String getGETApi(String permissionString) {
        //用冒号把permissionString分隔开
        String[] splitPermissions = permissionString.split(":");
        String api = "GET /" + splitPermissions[0] + "/" + splitPermissions[1] + "/" + splitPermissions[2];
        return api;
    }

    /**
     * 工具类，生成POST api
     *
     * @param permissionString
     * @return
     */
    private static String getPOSTApi(String permissionString) {
        //用冒号把permissionString分隔开
        String[] splitPermissions = permissionString.split(":");
        //只要前三个字段，如果有第四个字段，会抛弃掉
        String api = "POST /" + splitPermissions[0] + "/" + splitPermissions[1] + "/" + splitPermissions[2];
        return api;
    }


}


//全部的api
//    [
//            "admin:admin:update",
//            "admin:admin:list",
//            "admin:admin:read",
//            "admin:admin:delete",
//            "admin:admin:create",
//            "admin:role:permission:update",
//            "admin:role:update",
//            "admin:role:list",
//            "admin:role:read",
//            "admin:role:delete",
//            "admin:role:permission:get",
//            "admin:role:create",
//            "admin:storage:update",
//            "admin:storage:list",
//            "admin:storage:read",
//            "admin:storage:delete",
//            "admin:storage:create",
//            "admin:log:list",
//            "admin:brand:update",
//            "admin:brand:list",
//            "admin:brand:read",
//            "admin:brand:delete",
//            "admin:brand:create",
//            "admin:issue:update",
//            "admin:issue:list",
//            "admin:issue:delete",
//            "admin:issue:create",
//            "admin:order:read",
//            "admin:order:ship",
//            "admin:order:refund",
//            "admin:order:reply",
//            "admin:order:list",
//            "admin:category:update",
//            "admin:category:list",
//            "admin:category:read",
//            "admin:category:delete",
//            "admin:category:create",
//            "admin:keyword:update",
//            "admin:keyword:list",
//            "admin:keyword:read",
//            "admin:keyword:delete",
//            "admin:keyword:create",
//            "admin:collect:list",
//            "admin:config:wx:list",
//            "admin:config:wx:updateConfigs",
//            "admin:config:express:list",
//            "admin:config:express:updateConfigs",
//            "admin:config:mall:list",
//            "admin:config:mall:updateConfigs",
//            "admin:config:order:list",
//            "admin:config:order:updateConfigs",
//            "admin:ad:update",
//            "admin:ad:list",
//            "admin:ad:read",
//            "admin:ad:delete",
//            "admin:ad:create",
//            "admin:topic:update",
//            "admin:topic:list",
//            "admin:topic:read",
//            "admin:topic:delete",
//            "admin:topic:create",
//            "admin:coupon:listuser",
//            "admin:coupon:update",
//            "admin:coupon:list",
//            "admin:coupon:read",
//            "admin:coupon:delete",
//            "admin:coupon:create",
//            "admin:groupon:read",
//            "admin:groupon:update",
//            "admin:groupon:list",
//            "admin:groupon:delete",
//            "admin:groupon:create",
//            "admin:goods:read",
//            "admin:goods:update",
//            "admin:goods:list",
//            "admin:goods:delete",
//            "admin:goods:create",
//            "index:permission:write",
//            "index:permission:read",
//            "admin:stat:user",
//            "admin:stat:order",
//            "admin:stat:goods"
//            ]
